package booking

import (
	"Student_Mental/DBconfing"
	"Student_Mental/model"
	"database/sql"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
)

func GetBooking(c *gin.Context) {
	var bookingList []model.Booking
	teacher := c.Param("id")
	state := c.Param("state")
	sqlDb, _ := DBconfing.Mysql()
	defer sqlDb.Close()
	var rows *sql.Rows
	var err error
	if state != " " {
		rows, err = sqlDb.Query("SELECT * from booking where teacher_id=? and state=? ORDER BY booking_time ASC", teacher, state)
	} else {
		rows, err = sqlDb.Query("SELECT * from booking where teacher_id=? and state!=? ORDER BY booking_time ASC", teacher, 1)
	}
	if err != nil {
		println("结果为空")
		return
	}
	for rows.Next() {
		var booking model.Booking
		err := rows.Scan(&booking.Id, &booking.StudentId, &booking.TeacherId, &booking.Place, &booking.State, &booking.Content, &booking.BookingTime, &booking.CreateTime)
		sqlDb.QueryRow("(SELECT student_name FROM student WHERE id = ?)UNION(SELECT teacher_name FROM teacher WHERE id = ?)LIMIT 1;", booking.StudentId, booking.StudentId).Scan(&booking.StudentName)
		booking.StringTime = booking.CreateTime.Format("2006-01-02 15:04:05")
		if err != nil {
			log.Fatal(err)
		}
		switch booking.State {
		case 1:
			booking.StateName = "发起"
			break
		case 2:
			booking.StateName = "接受"
			break
		case 3:
			booking.StateName = "完成"
			break
		case 4:
			booking.StateName = "取消"
			break
		case 5:
			booking.StateName = "失效"
			break
		}
		bookingList = append(bookingList, booking)
	}
	c.JSON(200, gin.H{
		"code": 0,
		"data": bookingList,
	})
}

func UpdateBooking(c *gin.Context) {
	bookingId := c.Param("id")
	state := c.Param("state")
	sqlDb, _ := DBconfing.Mysql()
	defer sqlDb.Close()
	rs, err := sqlDb.Exec("UPDATE booking SET state=? WHERE id=?", state, bookingId)
	row, err := rs.RowsAffected()
	if err != nil {
		log.Println(err)
		c.JSON(200, gin.H{
			"code": 2,
			"msg":  "操作失败",
		})
		return
	}
	if row > 0 {
		c.JSON(200, gin.H{
			"code": 1,
			"msg":  "操作成功",
		})
	} else {
		c.JSON(200, gin.H{
			"code": 2,
			"msg":  "操作失败",
		})
	}
}

func UpdateBookingState(c *gin.Context) {
	redisClient, _ := DBconfing.ConnRedis()
	sendTimestamp := c.Param("sendTimestamp")
	newState := c.Param("newState")
	// 从 Redis 中取出所有元素
	listName := "60009"
	elems, err := redisClient.LRange(listName, 0, -1).Result()
	if err != nil {
		fmt.Println(err)
	}

	// 遍历所有元素，找到 SendTimestamp 匹配的元素
	for i, elem := range elems {
		var booking map[string]interface{}
		if err := json.Unmarshal([]byte(elem), &booking); err != nil {
			fmt.Println(err)
		}
		if booking["SendTimestamp"] == sendTimestamp {
			// 修改状态字段
			booking["content"].(map[string]interface{})["state"] = newState

			// 将修改后的元素重新设置回 Redis 中
			updatedElem, err := json.Marshal(booking)
			if err != nil {
				fmt.Println(err)
			}
			if err := redisClient.LSet(listName, int64(i), updatedElem).Err(); err != nil {
				fmt.Println(err)
			}
			c.JSON(200, gin.H{
				"code": 1,
				"msg":  "操作成功",
			})
			return
		}
	}
	c.JSON(200, gin.H{
		"code": 2,
		"msg":  "操作失败",
	})
}
